package org.demo.work;

import java.util.HashSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 任务管理器
 * @author  
 * @date    2010-10-27
 * @file    org.demo.work.WorkManagerImpl.java
 */
public class WorkManagerImpl implements WorkManager{
	
	// 线程池
	private ExecutorService threadPool;
	// 任务监听器
	private WorkListener listener;
	// 任务锁
	private final byte[] WORK_LOCK = new byte[0];
	// 当前任务
	private HashSet<Work> workInProgress = new HashSet<Work>();
	
	/**
	 *构造函数
	 */
	public WorkManagerImpl(WorkListener listener) {
		this.listener = listener;
		this.threadPool = Executors.newFixedThreadPool(10);				
	}
	
	/**
	 * 启动任务
	 * @param work
	 */
	public void startWork(Work work){
		
		// 确保不会有重复的任务被添加进来
		synchronized(WORK_LOCK){
			if (workInProgress.contains(work)){
				return;
			}
			workInProgress.add(work);
		}
		
		// 通知监听器 - 任务已接受
		listener.workAccepted(new WorkEvent(WorkEvent.WORK_ACCEPTED,work,null));
		
		// 放入线程池中执行任务
		threadPool.execute(new WorkProxy(work));
	}
	
	/**
	 * 完成任务
	 * @param work
	 */
	public void completeWork(Work work){
		synchronized(WORK_LOCK){
			workInProgress.remove(work);
			WORK_LOCK.notifyAll();
		}		
	}
	
	/**
	 * 关闭任务管理器，执行以前提交的任务，但不接受新任务
	 */
	public void shutdown() {
		threadPool.shutdown();
	}
	
	/**
	 * 任务代理
	 * @author 
	 *
	 */
	class WorkProxy implements Runnable{
		
		private Work work;
		
		/**
		 * 构造函数
		 * @param work
		 */
		public WorkProxy(Work work){
			this.work = work;
		}
		/**
		 * 执行任务
		 */
		@Override
		public void run() {
			// 通知监听器 - 任务已启动
			listener.workStarted(new WorkEvent(WorkEvent.WORK_STARTED,work,null));
			Exception exception = null;
			try {
				work.run();
			} catch (Exception e) {
				exception = e;
			}
			// 通知监听器 - 任务已完成
			listener.workCompleted(new WorkEvent(WorkEvent.WORK_COMPLETED, work, exception));
			// 删除任务
			WorkManagerImpl.this.completeWork(work);
		}
	}
}
